package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.commom.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


// 收货地址
@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> list() {
        LambdaQueryWrapper<Address> sb = new LambdaQueryWrapper<>();
        sb.eq(Address::getUserId, UserHolder.get().getId());
        return addressMapper.selectList(sb);
    }

    @Override
    public void add(Address address) {
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);
        addressMapper.insert(address);
    }

    @Override
    public void put(Address address) {
        Address address1 = new Address();
        address1.setIsDefault(0);
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());
        addressMapper.update(address1, qw);
        address.setIsDefault(1);
        addressMapper.updateById(address);

    }

    // 查询默认地址
    @Override
    public Address findDefault() {
        // 1.构建条件 select * from address_book where user_id = 1633299848511954946 and is_default = 1
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        qw.eq(Address::getIsDefault,1);
        // 2.执行查询
        return addressMapper.selectOne(qw);
    }

    // 回显收货地址
    @Override
    public Address selectAddress(Long id) {
        //SELECT * FROM address_book WHERE id = 1417414526093082626;
        LambdaQueryWrapper<Address> addressQW = new LambdaQueryWrapper<>();
        addressQW.eq(Address::getId, id);
        Address address = addressMapper.selectOne(addressQW);
        return address;
    }

    // 修改收货地址
    @Override
    public void saveAddress(Address newAddress) {
        // UPDATE  address_book SET xxx WHERE id =\
        LambdaQueryWrapper<Address> addressQW = new LambdaQueryWrapper<>();
        addressQW.eq(Address::getId, newAddress.getId());
        addressMapper.updateById(newAddress);
    }

}



